package com.csw.shuanfa.GlobalConfig.interceptor;


import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * 【全局拦截器】
 **/
@Component
@Slf4j
public class IPInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 在这里面也要判断token信息
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //限制几秒钟
        long second = 10;
        //多少次
        long maxCount = 2;
        //过滤ip,若用户在白名单内，则放行
        String ip = IPUtils.getRealIP(request);
        String key = this.getClass().getSimpleName() + ":Ips:" + ip;
        log.info("用户IP是 =>" + ip);
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String userIpCount = ops.get(key);
        long count = 0;
        if (Strings.isNotEmpty(userIpCount)) {
            count = Integer.valueOf(userIpCount);
        }
        //第一次访问
        if (count == 0) {
            count++;
            ops.set(key, String.valueOf(count), second, TimeUnit.SECONDS);
        } else if (count < maxCount) {
            count++;
            //永久和不存在返回都是0
            Long expireTime = stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
            if (expireTime <= 0) {//防止有人捣乱设置成永久
                stringRedisTemplate.delete(key);
            } else {
                ops.set(key, String.valueOf(count), expireTime, TimeUnit.SECONDS);
            }
        } else {
            //永久和不存在返回都是0
            Long expireTime = stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
            if (expireTime <= 0) {//防止有人捣乱设置成永久
                stringRedisTemplate.delete(key);
            }
            //超出访问次数
            log.info("访问的次数太多，请稍后访问###################################################################：ip={}", ip);
            return false;
        }

        /**
         * token信息判断
         */
//        String token = request.getHeader("Authorization");
//        String requestUrl = request.getRequestURI();
//        //排除掉登录路径
//        if (requestUrl.equals("/user/login")) {
//            return true;
//        } else {
//            //判断是否非空
//            if (token == null) {
//                throw new BusinessException("token不存在");
//            }
//
//            //校验是否在黑名单
//            if (TokenRevocationService.isTokenRevoked(token)) {
//                throw new BusinessException("token失效");
//            }
//            //直接解析token判断是否有效，或者直接从redis获取key判断
//            try {
//                JwtUtil jwtUtil = new JwtUtil();
//                Claims claims = jwtUtil.parsejwt(token, "key");
//                if (claims != null) {
//                    return true;
//                }
//            } catch (Exception e) {//解析失败或者失效
//                e.printStackTrace();
//                return false;
//            }
//        }




        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
